package com.bzyd.cloud.controller;

import com.alibaba.fastjson.JSON;
import com.bzyd.cloud.feign.ProductService;
import com.bzyd.cloud.pojo.Order;
import com.bzyd.cloud.pojo.Product;
import com.bzyd.cloud.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * OrderController
 * Created by Xianyue Dang on 2021/4/28
 */
@RestController
@Slf4j
public class OrderController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private OrderService orderService;
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private ProductService productService;

    //准备买1件商品
//    @GetMapping("/order/prod/{pid}")
    public Order order(@PathVariable("pid") Integer pid) {
        log.info(">>客户下单，这时候要调用商品微服务查询商品信息");

        //从nacos中获取服务地址
        //DiscoveryClient是专门负责服务注册和发现的，我们可以通过它获取注册到注册中心的所有服务
//        ServiceInstance serviceInstance = discoveryClient.getInstances("rocketmq-product").get(0);

        //自定义规则实现随机挑选服务
//        List<ServiceInstance> instances = discoveryClient.getInstances("rocketmq-product");
//        int index = new Random().nextInt(instances.size());
//        ServiceInstance serviceInstance = instances.get(index);
//        String url = serviceInstance.getHost() + ":" + serviceInstance.getPort();
//        log.info(">>从nacos中获取的微服务地址为：" + url);

        //Ribbon实现负载均衡，在创建RestTemplate处加@LoadBalanced注解后
        //直接使用微服务名字，从nacos中获取微服务地址
//        String url = "rocketmq-product";

        //通过restTemplate调用商品微服务
//        Product product = restTemplate.getForObject("http://" + url + "/product/" + pid, Product.class);
//        Product product = restTemplate.getForObject("http://localhost:8081/product/" + pid, Product.class);

        //通过feign调用微服务
        Product product = productService.findById(pid);
        if (product.getPid() == -1){
            Order order = new Order();
            order.setPname("下单失败");
            return order;
        }

        log.info(">>商品信息,查询结果:" + JSON.toJSONString(product));
        Order order = new Order();
        order.setUid(1);
        order.setUsername("测试用户");
        order.setPid(product.getPid());
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(1);
        orderService.save(order);
        return order;

    }


}
